package org.example.ThreadPool.ForkJoinPool;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class RecursiveTaskSty extends RecursiveTask<Integer> {
    private int limit = 4;
    private int firstIndex;
    private int lastIndex;

    public RecursiveTaskSty(int firstIndex, int lastIndex) {
        this.firstIndex = firstIndex;
        this.lastIndex = lastIndex;
    }

    @Override
    protected Integer compute() {
        int result = 0;
        int gap = lastIndex - firstIndex;
        boolean flag = gap <= limit;
        if (flag) {
            System.out.println(Thread.currentThread().getName());
            for (int i = firstIndex; i <= lastIndex; ++i) {
                result += i;
            }
        } else {
            int middleIndex = (firstIndex + lastIndex) / 2;

            RecursiveTaskSty leftTask = new RecursiveTaskSty(firstIndex, middleIndex);
            RecursiveTaskSty rightTask = new RecursiveTaskSty(middleIndex + 1, lastIndex);

            invokeAll(leftTask, rightTask); // 执行两个子任务

            result = leftTask.join() + rightTask.join(); // 获取两个子任务的结果
        }

        return result;
    }
    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(2); //空参，默认线程数等于CPU核心数
        RecursiveTaskSty task = new RecursiveTaskSty(1, 100);
        Integer invoke = forkJoinPool.invoke(task);
        System.out.println(invoke);
        forkJoinPool.shutdown();
    }
}
